"use client";

import { useEffect, useState } from "react";
import VideoForm from "@/app/components/admin/VideoForm";
import VideoTable from "@/app/components/admin/VideoTable";
import type { VideoItem, CategoryItem } from "@/app/types/video";

export default function AdminVideosPage() {
  const [videos, setVideos] = useState<VideoItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [editing, setEditing] = useState<VideoItem | null>(null);
  const [categories, setCategory] = useState<CategoryItem[]>([]);
  useEffect(() => {
    fetch(`/api/categories`)
      .then((res) => res.json())
      .then((data) => {
        setCategory(data.data);
      });
  }, []);

  async function fetchVideos() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/videos?size=100&page=1", {
        cache: "no-store",
      });
      const data = await res.json();
      if (!data.success) throw new Error(data.message || "获取视频失败");
      setVideos(data.data || []);
    } catch (e) {
      setError(e instanceof Error ? e.message : "未知错误");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchVideos();
  }, []);

  function handleCreateSuccess(newVideo: VideoItem) {
    setVideos((prev) => [newVideo, ...prev]);
  }

  function handleUpdateSuccess(updated: VideoItem) {
    setVideos((prev) => prev.map((v) => (v.id === updated.id ? updated : v)));
    setEditing(null);
  }

  async function handleDelete(id: string) {
    if (!confirm("确认删除该视频吗？")) return;
    try {
      const res = await fetch(`/api/videos/${id}`, { method: "DELETE" });
      const data = await res.json();
      if (!data.success) throw new Error(data.message || "删除失败");
      setVideos((prev) => prev.filter((v) => v.id !== id));
    } catch (e) {
      alert(e instanceof Error ? e.message : "删除失败");
    }
  }

  return (
    <div className="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold">视频管理</h1>
      </div>

      <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-800">
        <h2 className="mb-3 text-base font-medium">
          {editing ? "编辑视频" : "新增视频"}
        </h2>
        <VideoForm
          key={editing?.id || "create"}
          mode={editing ? "edit" : "create"}
          categories={categories}
          initialValue={editing || undefined}
          onCancel={() => setEditing(null)}
          onCreated={handleCreateSuccess}
          onUpdated={handleUpdateSuccess}
        />
      </div>

      <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-800">
        <div className="mb-3 flex items-center justify-between">
          <h2 className="text-base font-medium">视频列表</h2>
          <button
            className="rounded border border-zinc-300 px-3 py-1 text-sm hover:bg-zinc-50 dark:border-zinc-700 dark:hover:bg-zinc-900"
            onClick={fetchVideos}
          >
            刷新
          </button>
        </div>
        {error && <div className="mb-3 text-sm text-red-600">{error}</div>}
        <VideoTable
          loading={loading}
          videos={videos}
          onEdit={(v) => setEditing(v)}
          onDelete={(v) => handleDelete(v.id)}
        />
      </div>
    </div>
  );
}
